package com.daxidi.cn.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxidi.cn.annotation.LogAnnotation;
import com.daxidi.cn.entity.Bill;
import com.daxidi.cn.entity.Manager;
import com.daxidi.cn.entity.Member;
import com.daxidi.cn.entity.User;
import com.daxidi.cn.enums.LogTypeEnum;
import com.daxidi.cn.mapper.BillMapper;
import com.daxidi.cn.mapper.ManagerMapper;
import com.daxidi.cn.mapper.MemberMapper;
import com.daxidi.cn.mapper.UserMapper;
import com.daxidi.cn.params.AddMemberParam;
import com.daxidi.cn.params.UpdateMemberParam;
import com.daxidi.cn.service.IMemberService;
import com.daxidi.cn.service.IUserService;
import com.daxidi.cn.utils.JWTUtils;
import com.daxidi.cn.utils.RedisUtils;
import com.daxidi.cn.utils.ReturnResult;
import com.daxidi.cn.utils.ReturnResultUtils;
import com.daxidi.cn.utils.UuidUtils;
import com.daxidi.cn.vo.MemberIndexVo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author wsh
 * @since 2020-11-09
 */
@Log4j
@Api(tags = "会员模块接口")
@RestController
@RequestMapping("/api/v1/union/member")
public class MemberController {
    @Autowired
    private IMemberService memberService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private BillMapper billMapper;
    @Autowired
    private ManagerMapper managerMapper;

    @ApiOperation(value = "查询会员首页接口")
    @ApiResponses({
            @ApiResponse(code = 20000, message = "查询会员首页接口成功"),
            @ApiResponse(code = 119, message = "查询会员首页接口失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @GetMapping("/index/{memberId}")
    public ReturnResult memberIndex(@PathVariable("memberId") Long memberId) {
        try {
            Member member = memberMapper.selectById(memberId);
            MemberIndexVo memberIndexVo = new MemberIndexVo();
            memberIndexVo.setCode(member.getCode());
            memberIndexVo.setName(member.getName());
            //根据memberId查询user表
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("membe_id", memberId);
            User user = userMapper.selectOne(wrapper);
            memberIndexVo.setAvatarUrl(user.getAvatarurl());
            //为您节省
            QueryWrapper<Bill> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("membe_id", memberId);
            List<Bill> bills = billMapper.selectList(wrapper2);
            Double totalFree = 0.0;
            for (Bill bill : bills) {
                if (bill.getState() == 1) {
                    totalFree += bill.getFree();
                }
            }
            DecimalFormat df = new DecimalFormat("#####0.00");
            memberIndexVo.setTotalFree(df.format(totalFree));
            return ReturnResultUtils.returnSuccess(memberIndexVo);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询会员首页接口失败！ " + e);
            return ReturnResultUtils.returnFailMsg(119, "查询会员首页接口失败！");
        }
    }

    @LogAnnotation(content = "添加会员", type = LogTypeEnum.ADD)
    @ApiOperation(value = "添加会员接口")
    @ApiResponses({
            @ApiResponse(code = 108, message = "添加成功"),
            @ApiResponse(code = 109, message = "添加失败"),
            @ApiResponse(code = 257, message = "手机号已经被注册"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PostMapping
    public ReturnResult addMember(@RequestBody AddMemberParam addMemberParam) {
        try {
            //判断手机号是否存在
            QueryWrapper<Member> wrapper3 = new QueryWrapper<>();
            wrapper3.eq("mobile", addMemberParam.getMobile());
            if (memberMapper.selectList(wrapper3).size() > 0) {
                return ReturnResultUtils.returnFailMsg(257, "手机号已经被注册！");
            }
            Member member = new Member();
            member.setName(addMemberParam.getMemberName());
            String password = addMemberParam.getMobile().substring(addMemberParam.getMobile().length() - 6);
            member.setPassword(UuidUtils.sha1(password));
            member.setMobile(addMemberParam.getMobile());
            member.setCreatedAt(new Date());
            member.setIdCard(addMemberParam.getIdCard());
            member.setUnit(addMemberParam.getUnit());
            memberService.addMember(member);
            //添加code
            QueryWrapper<Member> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("mobile", addMemberParam.getMobile());
            Member member2 = memberMapper.selectOne(wrapper2);
            StringBuffer sb = new StringBuffer();
            sb.append("shgh");
            if (member2.getId().toString().length() > 4) {
                sb.append(member2.getId().toString().substring(member2.getId().toString().length() - 4));
            }
            sb.append(String.format("%04d", member2.getId()));
            String time = System.currentTimeMillis() + "";
            sb.append(time.substring(time.length() - 4));
            member2.setCode(sb.toString());
            memberMapper.updateById(member2);
            //添加user表
            QueryWrapper<Member> wrapper = new QueryWrapper<>();
            wrapper.eq("mobile", addMemberParam.getMobile());
            Member member1 = memberMapper.selectOne(wrapper);
            User user = new User();
            user.setMembeId(member1.getId());
            user.setCreatedAt(new Date());
            userMapper.insert(user);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("添加失败" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(109, "添加失败");
        }
    }

    @LogAnnotation(content = "删除会员", type = LogTypeEnum.DELETE)
    @ApiOperation(value = "根据会员id删除会员接口")
    @ApiResponses({
            @ApiResponse(code = 110, message = "删除成功"),
            @ApiResponse(code = 111, message = "删除失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @DeleteMapping("/{id}")
    public ReturnResult deleteMemberById(@PathVariable("id") Long id) {
        try {
            memberService.deleteMemberById(id);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("删除失败" + e);
            return ReturnResultUtils.returnFailMsg(111, "删除失败");
        }
    }

    @LogAnnotation(content = "修改会员信息", type = LogTypeEnum.UPDATE)
    @ApiOperation(value = "修改会员信息接口")
    @ApiResponses({
            @ApiResponse(code = 112, message = "修改成功"),
            @ApiResponse(code = 113, message = "修改失败"),
            @ApiResponse(code = 257, message = "手机号已经被注册"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @PutMapping
    public ReturnResult updateMemberById(@RequestBody UpdateMemberParam updateMemberParam) {
        try {
            //判断是否手机号重复
            QueryWrapper<Member> wrapper3 = new QueryWrapper<>();
            wrapper3.eq("id", updateMemberParam.getMemberId());
            Member member = memberMapper.selectOne(wrapper3);
            //判断是否手机号重复
            QueryWrapper<Member> wrapper = new QueryWrapper<>();
            wrapper.eq("mobile", updateMemberParam.getMobile());
            if (memberMapper.selectList(wrapper).size() > 0 && !updateMemberParam.getMemberId().equals(memberMapper.selectOne(wrapper).getId())) {
                return ReturnResultUtils.returnFailMsg(257, "手机号已经被注册！");
            }
            // 修改会员信息
            if (!StringUtils.isEmpty(updateMemberParam.getMemberName())) {
                member.setName(updateMemberParam.getMemberName());
            }
            if (!StringUtils.isEmpty(updateMemberParam.getMobile())) {
                member.setMobile(updateMemberParam.getMobile());
            }
            if (!StringUtils.isEmpty(updateMemberParam.getUnit())) {
                member.setUnit(updateMemberParam.getUnit());
            }
            member.setUpdatedAt(new Date());
            if (!StringUtils.isEmpty(updateMemberParam.getIdCard())) {
                member.setIdCard(updateMemberParam.getIdCard());
            }
            memberService.updateById(member);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("修改失败" + e);
            return ReturnResultUtils.returnFailMsg(113, "修改失败");
        }
    }

    @ApiOperation(value = "会员分页查询接口", notes = "count:  为 数据的总条数")
    @ApiResponses({
            @ApiResponse(code = 114, message = "查询成功"),
            @ApiResponse(code = 115, message = "查询失败"),
            @ApiResponse(code = 401, message = "未经授权"),
            @ApiResponse(code = 403, message = "被禁止"),
            @ApiResponse(code = 404, message = "请求路径没有货页面跳转路径不对")
    })
    @GetMapping
    public ReturnResult selectMembersByPage(@RequestParam(value = "name", required = false) String name,
                                            @RequestParam(value = "mobile", required = false) String mobile,
                                            @RequestParam(value = "idCard", required = false) String idCard,
                                            @RequestParam(value = "enable", required = false) Integer enable,
                                            @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "20") Integer limit) {
        try {
            Map map = memberService.selectMembersPage(name, mobile, idCard, enable, page, limit);
            return ReturnResultUtils.returnSuccess(map);
        } catch (Exception e) {
            log.error("查询失败" + e);
            return ReturnResultUtils.returnFailMsg(115, "查询失败");
        }
    }

    @ApiOperation(value = "会员下线接口")
    @PutMapping("/offlineMember/{id}")
    public ReturnResult offline(@PathVariable(value = "id") Long id) {
        try {
            Member member = memberMapper.selectById(id);
            member.setEnable(0);
            memberMapper.updateById(member);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("会员下线失败" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(715, "会员下线失败！");
        }
    }

    @ApiOperation(value = "会员上线接口")
    @PutMapping("/onlineMember/{id}")
    public ReturnResult online(@PathVariable(value = "id") Long id) {
        try {
            Member member = memberMapper.selectById(id);
            member.setEnable(1);
            memberMapper.updateById(member);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("会员上线失败" + e);
            e.printStackTrace();
            return ReturnResultUtils.returnFailMsg(715, "会员上线失败！");
        }
    }

    @ApiOperation(value = "根据code查询member和user表")
    @GetMapping("/selectMember/{code}")
    public ReturnResult selectMember(@PathVariable("code") String code) {
        Member member = memberService.selectMemberByCode(code);
        User user = userService.selectUserByMemberId(member.getId());
        Map map = new HashMap();
        map.put("member", member);
        map.put("user", user);
        return ReturnResultUtils.returnSuccess(map);
    }

    @ApiOperation(value = "根据会员id查看单个会员接口")
    @GetMapping("/{id}")
    public ReturnResult selectMemberById(@PathVariable("id") Long id) {
        try {
            Member member = memberService.selectMemberById(id);
            return ReturnResultUtils.returnSuccess(member);
        } catch (Exception e) {
            log.error("查询失败" + e);
            return ReturnResultUtils.returnFailMsg(115, "查询失败");
        }
    }

    @LogAnnotation(content = "重置会员密码", type = LogTypeEnum.UPDATE)
    @ApiOperation(value = "重置密码接口")
    @PutMapping("/updatePassword/{id}")
    public ReturnResult updatePassword(@PathVariable("id") Long id, HttpServletRequest request) {
        try {
            String token = request.getHeader("token");
            Claims claim = JWTUtils.getClaim(token);
            String name = claim.get("mobile").toString();
            QueryWrapper<Manager> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("username", name);
            Manager manager = managerMapper.selectOne(wrapper2);
            if (ObjectUtils.isEmpty(manager)) {
                return ReturnResultUtils.returnFailMsg(631, "非管理员身份！");
            }

            QueryWrapper<Member> wrapper = new QueryWrapper<>();
            wrapper.eq("id", id);
            Member member = memberMapper.selectOne(wrapper);
            String password = member.getMobile().substring(member.getMobile().length() - 6);
            member.setPassword(UuidUtils.sha1(password));
            memberMapper.updateById(member);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("重置密码失败" + e);
            return ReturnResultUtils.returnFailMsg(115, "重置密码失败");
        }
    }

    @LogAnnotation(content = "修改会员密码", type = LogTypeEnum.SELECT)
    @ApiOperation(value = "修改会员密码接口")
    @PostMapping("/changeMemberPwd")
    public ReturnResult changeMemberPwd(@RequestParam Long memberId, @RequestParam String pwd) {
        try {
            Member member = memberMapper.selectById(memberId);
            member.setPassword(UuidUtils.sha1(pwd));
            memberMapper.updateById(member);
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("修改会员密码失败！" + e);
            return ReturnResultUtils.returnFailMsg(561, "修改会员密码失败！");
        }
    }

    @LogAnnotation(content = "导出会员信息", type = LogTypeEnum.SELECT)
    @ApiOperation(value = "会员信息导出接口")
    @GetMapping("/downloadMember")
    public ReturnResult downloadMember() {
        try {
            List<Member> members = memberMapper.selectList(null);
            return ReturnResultUtils.returnSuccess(members);
        } catch (Exception e) {
            log.error("导出失败" + e);
            return ReturnResultUtils.returnFailMsg(198, "导出失败");
        }
    }

    @ApiOperation("会员信息导入接口")
    @PostMapping("/importMember")
    public ReturnResult importMember(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            ImportParams importParams = new ImportParams();
            //  声明 有一行是字段名   不读取
            importParams.setTitleRows(0);
            importParams.setHeadRows(1);
            List<AddMemberParam> members = ExcelImportUtil.importExcel(inputStream, AddMemberParam.class, importParams);
            //批量添加
            System.out.println("members = " + members);
            members.forEach(m -> addMember(m));
            return ReturnResultUtils.returnSuccess();
        } catch (Exception e) {
            log.error("导入失败" + e);
            return ReturnResultUtils.returnFailMsg(197, "导入失败");
        }
    }
}
